package com.hillstone.hsm.swtool.shellp.service.passwd.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.hillstone.hsm.swtool.shellp.constant.Constant;
import com.hillstone.hsm.swtool.shellp.service.passwd.IPasswdService;
import com.hillstone.hsm.swtool.shellp.util.CollectionUtil;
import com.hillstone.hsm.swtool.shellp.util.CommandUtil;
import com.hillstone.hsm.swtool.shellp.web.controller.ShellPasswdController;

@Service(value = "passwdService")
public class PasswdServiceImpl implements IPasswdService {
	
	private static Logger logger = Logger.getLogger(PasswdServiceImpl.class);

	@Override
	public String getShellPasswd(String sn, String date) {
		String cmd = "/usr/sbin/generatePasswd.sh shell " + sn + " " + date + "";
		Map<String, List<String>> resultMap = CommandUtil.goodExecutorCmd("/bin/bash", "-c", cmd);
		List<String> errorList = resultMap.get(Constant.ERROR);
		if(CollectionUtil.isNotEmpty(errorList)) {
			logger.error("exec command error:" + cmd);
			return "exec command error";
		}
		
		List<String> successList = resultMap.get(Constant.SUCCESS);
		if(CollectionUtil.isEmpty(successList)) {
			logger.error("result is empty:" + cmd);
			return "";
		}
		
		String resultStr = successList.get(0);
		logger.error("result is " + resultStr);
		return resultStr.replaceAll("passwd:", "");
	}
	
	@Override
	public String getRootPasswd(String sn) {
		String date = "20180331";
		Map<String, List<String>> resultMap = CommandUtil.goodExecutorCmd("/bin/bash", "-c", "/usr/sbin/generatePasswd.sh root " + sn + " " + date + "");
		List<String> errorList = resultMap.get(Constant.ERROR);
		if(CollectionUtil.isNotEmpty(errorList)) {
			return "exec command error";
		}
		
		List<String> successList = resultMap.get(Constant.SUCCESS);
		if(CollectionUtil.isEmpty(successList)) {
			return "";
		}
		
		String resultStr = successList.get(0);
		return resultStr.replaceAll("passwd:", "");
	}
	
}
